#include "user.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h> // Needed for snprintf

// 加载所有用户信息到链表，返回用户数量
// filename is expected to be the base filename (e.g., "users.dat")
int load_users(const char* filename, UserNode** head) {
    char full_path[1024];
    // Construct the full path using the macro defined in CMakeLists.txt
    // SOURCE_DATA_PATH should be defined like "/path/to/project/data"
    snprintf(full_path, sizeof(full_path), "%s/%s", SOURCE_DATA_PATH, filename);

    FILE* fp = fopen(full_path, "rb");
    if (!fp) {
        // Optional: Print an error message if file couldn't be opened
        // perror(full_path);
        *head = NULL;
        return 0;
    }
    User temp;
    int count = 0;
    *head = NULL;
    UserNode* tail = NULL;
    while (fread(&temp, sizeof(User), 1, fp) == 1) {
        UserNode* node = (UserNode*)malloc(sizeof(UserNode));
        if (!node) break;
        node->data = temp;
        node->next = NULL;
        if (*head == NULL) {
            *head = node;
        } else {
            tail->next = node;
        }
        tail = node;
        count++;
    }
    fclose(fp);
    return count;
}

// 保存所有用户信息到文件，返回保存的用户数量
// filename is expected to be the base filename (e.g., "users.dat")
int save_users(const char* filename, UserNode* head) {
    char full_path[1024];
    // Construct the full path using the macro defined in CMakeLists.txt
    snprintf(full_path, sizeof(full_path), "%s/%s", SOURCE_DATA_PATH, filename);

    FILE* fp = fopen(full_path, "wb");
    if (!fp) {
        // Optional: Print an error message if file couldn't be opened
        // perror(full_path);
        return 0;
    }
    int count = 0;
    UserNode* p = head;
    while (p) {
        if (fwrite(&p->data, sizeof(User), 1, fp) != 1) break;
        p = p->next;
        count++;
    }
    fclose(fp);
    return count;
}

// 添加新用户到链表尾部，若编号已存在则不添加，返回1成功，0已存在
int add_user(UserNode** head, const User* new_user) {
    if (find_user_by_id(*head, new_user->id)) {
        // 已存在该编号用户，不添加
        return 0;
    }
    UserNode* node = (UserNode*)malloc(sizeof(UserNode));
    if (!node) return 0;
    node->data = *new_user;
    node->next = NULL;
    if (*head == NULL) {
        *head = node;
    } else {
        UserNode* p = *head;
        while (p->next) p = p->next;
        p->next = node;
    }
    return 1;
}

// 根据用户编号删除用户，成功返回1，失败返回0
int delete_user(UserNode** head, int user_id) {
    UserNode* p = *head, *prev = NULL;
    while (p) {
        if (p->data.id == user_id) {
            if (prev) prev->next = p->next;
            else *head = p->next;
            free(p);
            return 1;
        }
        prev = p;
        p = p->next;
    }
    return 0;
}

// 查找用户，返回指向该节点的指针，未找到返回NULL
UserNode* find_user_by_id(UserNode* head, int user_id) {
    while (head) {
        if (head->data.id == user_id) return head;
        head = head->next;
    }
    return NULL;
}

// 修改用户信息，成功返回1，失败返回0
int update_user(UserNode* head, const User* updated_user) {
    UserNode* node = find_user_by_id(head, updated_user->id);
    if (!node) return 0;
    node->data = *updated_user;
    return 1;
}

// 打印所有用户信息（调试用）
void print_all_users(UserNode* head) {
    printf("编号\t姓名\t类型\t地址\t电话\n");
    while (head) {
        printf("%d\t%s\t%s\t%s\t%s\n",
            head->data.id,
            head->data.name,
            head->data.type == USER_TYPE_ADMIN ? "管理员" : "普通用户",
            head->data.address,
            head->data.phone
        );
        head = head->next;
    }
}

// 释放链表内存
void free_all_users(UserNode* head) {
    while (head) {
        UserNode* tmp = head;
        head = head->next;
        free(tmp);
    }
}

// 登录校验：成功返回1并输出用户信息，失败返回0
int check_user_login(UserNode* head, const char* name, const char* password, User* out_user) {
    while (head) {
        if (strcmp(head->data.name, name) == 0 && strcmp(head->data.password, password) == 0) {
            if (out_user) *out_user = head->data;
            return 1;
        }
        head = head->next;
    }
    return 0;
}